package com.songqintuan.platform.navigation;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIParameter;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import org.richfaces.component.UIPanelMenu;
import org.richfaces.component.UIPanelMenuGroup;
import org.richfaces.component.UIPanelMenuItem;

import com.songqintuan.common.bean.MenuState;
import com.songqintuan.common.constant.GlobalConstants;
import com.songqintuan.common.util.SpringFacesUtil;
import com.songqintuan.common.util.UIComponentUtil;
import com.songqintuan.model.po.AuthorityResources;
import com.songqintuan.persist.service.hibernate.IAuthorityResourcesService;
import com.songqintuan.platform.common.constant.PlatformManageBeanConstants;
import com.songqintuan.platform.common.constant.PlatformSpringBeanConstants;
import com.songqintuan.platform.tree.ResourceDTree;
@ManagedBean(name="userAccessPanelMenu")
@SessionScoped
public class UserAccessPanelMenuPageBean implements Serializable {

	/**
	 * 
	 */
	private static final String WEBAPP = "WEB-INF/";
	private static final String VIEW_PARAMETER = "urlPath";
	private static final long serialVersionUID = 1L;
	private MenuState menuState;
    private UIPanelMenu panelMenu;  
    Map<Long, UIPanelMenuGroup> parentPanel = new HashMap<Long, UIPanelMenuGroup>();  
  
    Map<String, Boolean> menu = new HashMap<String, Boolean>();  
    private Map<String, String> menuUrl = new HashMap<String, String>();
    private String currentMenuId ;
    List<AuthorityResources> menuItems;  
    Map<String, AuthorityResources> menuGroups;

	public MenuState getMenuState() {  
        return menuState;  
    }  
  
    public void setMenuState(MenuState menuState) {  
        this.menuState = menuState;  
    }  
    public UIPanelMenu getPanelMenu() {
    	if (panelMenu == null)
        {
            loadMenu();
        }
        return panelMenu;  
    }  
  
    public void setPanelMenu(UIPanelMenu panelMenu) {
        this.panelMenu = panelMenu;
    }  

	public Map<String, String> getMenuUrl() {
		return menuUrl;
	}

	public String getCurrentMenuId() {
		return currentMenuId;
	}

	public void setCurrentMenuId(String currentMenuId) {
		this.currentMenuId = currentMenuId;
	}

	public void setMenuUrl(Map<String, String> menuUrl) {
		this.menuUrl = menuUrl;
	}

	// 用于存储菜单的状态而触发的事件  
    public void select(ActionEvent event) {  
        menuState.setSelectedMenuItem(event.getComponent().getId());
        List<UIComponent> componets = event.getComponent().getChildren();
        Iterator<UIComponent> it = componets.iterator();
        while (it.hasNext()) {
        	UIComponent  commponent = it.next();
        	if (commponent.getClass().getName().equals(UIParameter.class.getName())) {
        		UIParameter pa = (UIParameter) commponent;
        		this.setCurrentMenuId(pa.getValue().toString());
        		break;
        	}
        }
        System.out.println("listener============");
    }
    public String goUrl(){
    	String menuKey = this.getCurrentMenuId();
    	String goUrl = this.getMenuUrl().get(menuKey);
    	HandleUrlPageBean handleUrlPage =(HandleUrlPageBean) SpringFacesUtil.getManagedBean(PlatformManageBeanConstants.HANDLE_URL_PAGE_BEAN);
    	handleUrlPage.getUrlControlBean().setNextUrl(goUrl);
    	return (null == goUrl)? null:goUrl + "?faces-redirect=true";
    }
    public UserAccessPanelMenuPageBean(){
        loadMenu();
    }
  
    // 载入菜单  
    private void loadMenu() {
  
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");   
        FacesContext fc = SpringFacesUtil.getFacesContext();
    	Application app = fc.getApplication();
    	if (null != panelMenu && !(panelMenu.getChildren().isEmpty())) {
    		panelMenu.getChildren().clear();
    	} else {
    		panelMenu = (UIPanelMenu) app.createComponent(fc,UIPanelMenu.COMPONENT_TYPE, "org.richfaces.PanelMenuRenderer");
    	}
        panelMenu.setId("userPanelMenu");
        //panelMenu.setGroupMode(PanelMenuMode.ajax);
        //panelMenu.setItemMode(PanelMenuMode.ajax);
        panelMenu.setImmediate(true);
        menuItems = new ArrayList<AuthorityResources>();  
        menuGroups = new HashMap<String, AuthorityResources>();  
        
        Map<String, Boolean> menu = new HashMap<String, Boolean>(); 
          
  
        // 添加该用户的所有菜单项目到List和Hash表中 
        Object ob = SpringFacesUtil.getSpringBean(PlatformSpringBeanConstants.AUTHORITY_RESOURCES_SERVICE_BEAN_NAME);
        IAuthorityResourcesService<AuthorityResources,Long> authorityResourcesService = (IAuthorityResourcesService<AuthorityResources,Long>)ob;
        authorityResourcesService.setEntityClass(AuthorityResources.class);
        authorityResourcesService.setPKClass(Long.class);
        List<AuthorityResources> Menuitems = authorityResourcesService.getAll("id", GlobalConstants.ORDER_BY_ASC_TRUE);
        //如果menuurl不为null 则清空，重新获取
        if ( !(this.getMenuUrl().isEmpty())) {
        	this.getMenuUrl().clear();
        }
        for (AuthorityResources menuitem : Menuitems) {  
            if ("I".equals(menuitem.getType())){  
                menuItems.add(menuitem); 
                this.getMenuUrl().put(menuitem.getId().toString(), menuitem.getUrl());
            }else{  
                menuGroups.put(menuitem.getId().toString(), menuitem);  
            }     
        }  
          
        // 添加所有的叶子节点  
        for (AuthorityResources menuitem : menuItems) { 
            UIPanelMenuItem panelLeafItem = (UIPanelMenuItem) app.createComponent(fc,
    				UIPanelMenuItem.COMPONENT_TYPE,

    				"org.richfaces.PanelMenuItemRenderer");
            panelLeafItem.setId("menu" + "_" + String.valueOf(menuitem.getId()));
            panelLeafItem.setName("menu" + "_" + String.valueOf(menuitem.getId()));
            panelLeafItem.setLabel(menuitem.getLabel());
            //panelLeafItem.setMode(PanelMenuMode.ajax);
            panelLeafItem.setImmediate(true);
            // 给叶子节点添加事件监听和Action
            panelLeafItem.addActionListener(UIComponentUtil.createActionListener("#{userAccessPanelMenu.select}"));
            panelLeafItem.setActionExpression(UIComponentUtil.createAction("#{userAccessPanelMenu.goUrl}", String.class));  
            //panelLeafItem.setOnclick("iframeSrc();");
            UIParameter param = new UIParameter();
            param.setName("url");
            param.setValue(menuitem.getId()); 
            panelLeafItem.getChildren().add(param); //Add Param to Item
            // 添加该叶子节点的父节点  
            addPanel(fc,panelLeafItem, menuitem);  
        }
        //需要遍历　parentPanel　加入到　panel menu中去
        /*Iterator iter = parentPanel.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            Object key = entry.getKey();
            Object val = entry.getValue();
            panelMenu.getChildren().add((UIPanelMenuGroup)val); 
        } */
        // 设置菜单组的状态绑定  
        menuState = new MenuState();
        menuState.setMenu(menu);  
        System.out.println("Create Menu Ended:" + fmt.format(System.currentTimeMillis()));  
    }  
  
    private void addPanel(FacesContext fc,UIComponent subPanel, AuthorityResources node) {
        if (null !=node.getPid() && !"".equals(node.getPid()) && (node.getPid() != 0)) {
        	AuthorityResources parentNode = menuGroups.get(String.valueOf(node.getPid().intValue()));
        	if ( null != parentNode) {
	            
	            Application app = fc.getApplication();
	            UIPanelMenuGroup newPanel;
	            if (parentPanel.containsKey(parentNode.getId())) {  
	                newPanel = parentPanel.get(parentNode.getId());  
	                newPanel.getChildren().add(subPanel);  
	            } else {  
	                newPanel = (UIPanelMenuGroup) app.createComponent(fc,
	        				UIPanelMenuGroup.COMPONENT_TYPE,
	
	        				"org.richfaces.PanelMenuGroupRenderer");   
	                newPanel.setId("menu" + "_" + String.valueOf(parentNode.getId()));
	                newPanel.setName("menu" + "_" + String.valueOf(parentNode.getId()));  
	                newPanel.setLabel(parentNode.getLabel());
	                //newPanel.setMode(PanelMenuMode.ajax);
	                newPanel.setImmediate(true);
	                newPanel.setExpanded(Boolean.TRUE);
	                newPanel.getChildren().add(subPanel);  
	                parentPanel.put(parentNode.getId(), newPanel);  
	            }  
	            // 添加该Group节点的父节点  
	            
	            addPanel(fc,newPanel, parentNode);
	           
        	}
        } else {  //该叶子节点的父节点就是panel menu

        	Application app = fc.getApplication();
        	ExpressionFactory exp = app.getExpressionFactory();
            //设置该菜单组的Value属性值 
        	ValueExpression value = exp.createValueExpression(fc.getELContext(),
        			"#{userAccessPanelMenu.menuState.menu['"  
                            + ((UIPanelMenuGroup) subPanel)  
                                    .getLabel() + "']}", String.class);
            subPanel.setValueExpression("value", value);  
              
            // 把根Group节点添加到菜单中  
            panelMenu.getChildren().add(subPanel);  
  
            // 设置该菜单组的状态初始值  
            menu.put(((UIPanelMenuGroup) subPanel).getLabel(), false);  
        }  
    }  

    
    public void destroy() {  
    }
    private String getViewParameter(String name) {
        FacesContext fc = FacesContext.getCurrentInstance();
        String param = (String) fc.getExternalContext().getRequestParameterMap().get(name);
        if (param != null && param.trim().length() > 0) {
            return param;
        } else {
            return null;
        }
    }
    public String getCurrentUrlPath() {
        String id = getViewParameter(VIEW_PARAMETER);
        return id;
    }
    public String getCurrentURI() {
    	
    	String result = null;
        FacesContext context = FacesContext.getCurrentInstance();

        NavigationHandler handler = context.getApplication().getNavigationHandler();

        if (handler instanceof ConfigurableNavigationHandler) {
            ConfigurableNavigationHandler navigationHandler = (ConfigurableNavigationHandler) handler;

            NavigationCase navCase = navigationHandler.getNavigationCase(context, null, WEBAPP + getCurrentUrlPath());
            if (null != navCase) {
            	result = navCase.getToViewId(context);
            }
        }

        return result;
    }
}
